package com.test.profile.controller;

import com.shop.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import static com.shop.util.Constants.FLAG;

public class BaseServlet  extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodStr = req.getParameter("method");
        if(methodStr == null||"".equals(methodStr)){
            methodStr = "login";
        }
        Class clazz = this.getClass();
        try {
            //使用clazz获取方法对象方法
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);
            //执行从类中获取中的方法对象，接收方法执行结果
            Object result = method.invoke(this, req, resp);
//            判断是否为空
            if(result!=null){
                String jump = (String) result;
//                判断跳转类型是否为重定向
                if(jump.startsWith("forword:")){
//                    为请求转发
                    String path = jump.substring(jump.indexOf(":") + 1);
                    req.getRequestDispatcher(path).forward(req, resp);
                }else if(jump.startsWith("redirect")){
//                    为重定向
                    String path = jump.substring(jump.indexOf(":") + 1);
                    resp.sendRedirect(path);
                }else{
//                    判断为其他类型的返回值，那么通过流写回到浏览器页面
                    resp.getWriter().println(jump);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}



